from demo import test
from lib import *
from row import Row
from thing import *

class Table:   
  def __init__(o): o.header=[]   
  def clone(o,lists=[]) :
    t= Table()
    t.ready([one.name for one in o.header])
    for lst in lists: t.put(lst)
    return t
  def ready(o,lst,prep=lambda x: x) :
    o.data=[]; o.nums=[]; o.syms=[]
    o.header=[]
    for i,name in enumerate(lst):
      isKlass = i == (len(lst) - 1)
      if "$" in name: 
        o.nums.append(i); new= Num(i,name,prep,isKlass)
      else:
        o.syms.append(i); new= Sym(i,name,isKlass)
      o.header.append(new)
    return o
  def put(o,lst) :
    if len(lst) == len(o.header):
        tmp = [o.header[i].put(x) for i,x in enumerate(lst)]
        o.data.append(Row(o,tmp))
  def rowProxy(o,lst):
    if isinstance(lst,Row):
      return lst
    for col in o.nums: 
      if lst[col] != '?':
        lst[col] = o.header[col].prep(lst[col])     
    return Row(o,lst)
  def slurp(o,file) :
    for lst in rows(file):
      if not o.header: o.ready(lst,prep=float)
      else           : o.put(lst)
    return o
  def disretize(o,bins=5) :
    tmp = zip(*o.data)
    for i in o.nums : 
      b = o.header[i].getBreaks(tmp[i],bins)
      tmp[i] = [bin(num,o,b) for x in tmp[i]]
    o.data = zip(*tmp)
  def closest(o,r1, best = 10**32,
                    better=lambda x,y: x < y):
    out=None
    for r2 in o.data:
      if r1.id != r2.id:
        tmp = r1 - r2
        if not out: 
           best,out=tmp,r2
        else:
          if better(tmp,best): 
            best,out=tmp,r2
    return out
  def furthest(o,r1)  : 
    return o.closest(r1,-1,lambda x,y: x > y)


